<template>
  <el-card shadow="never">
    <!-- 头部 -->
    <div slot="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }"> <i class="el-icon-house"></i> 首页</el-breadcrumb-item>
        <el-breadcrumb-item>参数管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 主体内容 -->
    <el-alert show-icon
              title="注意：只允许为三级分类设置相关参数"
              type="warning">
    </el-alert>
    <br>
    <!-- 级联选择器 -->
    <p>
      请选择分类： <el-cascader v-model="cateList"
                   :options="allCateList"
                   @change="changeCate"
                   clearable
                   :props="{
                         label:'cat_name',
                         value:'cat_id',
                         children:'children'
                       }"></el-cascader>
    </p>
    <!-- tab组件 -->
    <el-tabs v-model="activeName"
             @tab-click="changeCate">
      <el-tab-pane label="动态参数"
                   name="many">
        <el-button type="primary"
                   :disabled="btnDisabled"
                   @click="isAddShow=true">添加动态参数</el-button>
        <br> <br>
        <!-- 动态参数表格 -->
        <el-table :data="manyList"
                  border>
          <el-table-column type="expand"
                           width="120">
            <template slot-scope="scope">
              <!-- 折叠列渲染参数值 -->
              <!-- 标签 -->
              <el-tag v-for="(item,index) in scope.row.attr_vals"
                      :key="index"
                      @close="delAttrVal(scope.row,index)"
                      closable>{{item}}</el-tag>
              <!-- 输入框 -->
              <el-input class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        size="small">
              </el-input>
              <!-- 增加按钮 -->
              <el-button v-else
                         class="button-new-tag"
                         size="small"
                         type="primary"
                         @click="showInput(scope.row)">增加</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index"
                           label="序号"
                           width="160"></el-table-column>
          <el-table-column prop="attr_name"
                           label="参数名"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="success"
                         size="small"
                         circle
                         icon="el-icon-edit"></el-button>
              <el-button type="danger"
                         size="small"
                         circle
                         @click="delAttr(scope.row)"
                         icon="el-icon-delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性"
                   name="only">
        <el-button type="primary"
                   :disabled="btnDisabled"
                   @click="isAddShow=true">添加静态属性</el-button>
        <br> <br>
        <!-- 静态属性表格 -->
        <el-table :data="onlyList"
                  border>
          <el-table-column type="expand"
                           width="120">
            <!-- 折叠列渲染参数值 -->
            <template slot-scope="scope">
              <!-- 折叠列渲染参数值 -->
              <!-- 标签 -->
              <el-tag v-for="(item,index) in scope.row.attr_vals"
                      :key="index"
                      @close="delAttrVal(scope.row,index)"
                      closable>{{item}}</el-tag>
              <!-- 输入框 -->
              <el-input class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        size="small">
              </el-input>
              <!-- 增加按钮 -->
              <el-button v-else
                         class="button-new-tag"
                         size="small"
                         type="primary"
                         @click="showInput(scope.row)">增加</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index"
                           label="序号"
                           width="160"></el-table-column>
          <el-table-column prop="attr_name"
                           label="参数名"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="success"
                         size="small"
                         circle
                         icon="el-icon-edit"></el-button>
              <el-button type="danger"
                         size="small"
                         circle
                         @click="delAttr(scope.row)"
                         icon="el-icon-delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加动态或静态参数 -->
    <el-dialog :title="this.activeName === 'many' ? '添加动态属性':'添加静态参数'"
               :visible.sync="isAddShow"
               width="30%">
      <!-- 表单 -->
      <el-form :model="addFormInfo"
               ref="addFormInfo"
               :rules="addFormRules"
               label-width="100px"
               size="normal">
        <el-form-item label="参数名称"
                      prop="attr_name">
          <el-input v-model="addFormInfo.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="isAddShow = false">取消</el-button>
        <el-button type="primary"
                   @click="addSubmit">确定</el-button>
      </span>
    </el-dialog>

  </el-card>
</template>

<script>
export default {
  name:'Params',
  data () {
    return {
      cateList: [], // 选择的分类信息
      allCateList:[], // 所有分类数据
      activeName:'many',
      manyList:[], // 动态属性
      onlyList:[], // 静态参数
      isAddShow:false,
      addFormInfo:{
        attr_name:''
      },
      addFormRules:{
        attr_name:[{ required:true, message:'请输入参数名', trigger:'blur' }]
      }
    }
  },
  created () {
    this.getAllCateList()
  },
  computed: {
    // 按钮是否禁用
    btnDisabled () {
      return this.cateList.length === 0
    },
    // 分类ID
    cateId () {
      if (this.cateList.length === 3) {
        return this.cateList[2]
      } else {
        return ''
      }
    }
  },
  methods: {
    // 获取所有分类数据
    async getAllCateList () {
      const { data:res } = await this.$axios.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.allCateList = res.data
    },
    // 当级联发生变化触发、tab切换的时候都执行changeCate
    async changeCate () {
      // 如果不是三级就跳出，要将所有内容置空
      if (this.cateList.length !== 3) {
        this.cateList = []
        this.manyList = []
        this.onlyList = []
        return false // 后面知道
      }
      // 是三级就获取对应三级的静态参数和动态属性
      // 是静态还是动态 取决于 this.activeName
      const { data:res } = await this.$axios.get('/categories/' + this.cateId + '/attributes', {
        params:{ sel:this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 赋值, 属性名通过activeName拼接的方式放到对应的列表变量

      // 1. 处理数据中的attr_vals字段，将其变成数组
      // 2. 每行数据增加属性自己的inputValue 和  inputVisible
      const list = res.data.map(val => {
        val.attr_vals = val.attr_vals ? val.attr_vals.split(',') : []
        val.inputVisible = false
        val.inputValue = ''
        return val
      })
      this[this.activeName + 'List'] = list
    },
    // 添加参数
    addSubmit () {
      this.$refs.addFormInfo.validate(async valid => {
        if (!valid) return
        const { data:res } = await this.$axios.post(`categories/${this.cateId}/attributes`, {
          attr_name:this.addFormInfo.attr_name,
          attr_sel:this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$refs.addFormInfo.resetFields()
        this.isAddShow = false
        // 拉取数据
        this.changeCate()
      })
    },
    // 删除参数
    async delAttr (val) {
      try {
        await this.$confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const { data:res } = await this.$axios.delete(`/categories/${val.cat_id}/attributes/${val.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.changeCate()
      } catch (error) {
        this.$message.info('取消删除')
      }
    },
    // 打开添加参数值输入框
    showInput (row) { // row表示当前行的数据
      row.inputVisible = true // true 了 el-input组件才去渲染
      // this.$nextTick 等到DOM渲染完成之后再做某个事件
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 参数值提交
    async handleInputConfirm (row) {
      // 1.空值处理
      if (!row.inputValue) {
        row.inputVisible = false
        return false
      }
      // 2.将输入框的值增加到当前行的attr_vals  ，增加参数值操作其本质是修改参数里面的attr_vals字段内容，所以要提交完成的所有参数内容
      row.attr_vals.push(row.inputValue)
      // 3.发送请求
      // eslint-disable-next-line camelcase
      const attr_vals = row.attr_vals.join(',')
      const { data:res } = await this.$axios.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals // 提交的是完成所有参数的字符串
      })
      if (res.meta.status !== 200) return this.$message.error(res.msg)
      this.$message.success(res.meta.msg)
      row.inputValue = ''
      row.inputVisible = ''
    },
    async delAttrVal (row, idx) {
      try {
        await this.$confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // eslint-disable-next-line camelcase
        let attr_vals = [...row.attr_vals]
        attr_vals.splice(idx, 1)
        // eslint-disable-next-line camelcase
        attr_vals = attr_vals.join(',')
        const { data:res } = await this.$axios.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
          attr_name:row.attr_name,
          attr_sel:row.attr_sel,
          attr_vals // 提交的是完成所有参数的字符串
        })
        if (res.meta.status !== 200) return this.$message.error(res.msg)
        this.$message.success(res.meta.msg)
        row.attr_vals.splice(idx, 1)
      } catch (error) {
        this.$message.info('取消删除')
      }
    }
  }
}
</script>

<style scoped>
.el-tag{
  margin-right: 5px;
}
.input-new-tag{
  width: 200px;
  display: inline-block;
}
</style>
